package com.gdzn.netty.handler;


import com.gdzn.netty.channel.ChannelTcpMap;
import com.gdzn.common.core.utils.DateUtils;
import com.gdzn.netty.service.IDeviceService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用于处理客户端与服务端的心跳，在客户端空闲（如飞行模式)时关闭channel，节省服务器资源
 *
 * @author cxz kenny
 */
@Slf4j
@Component
public class TcpHeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private IDeviceService deviceService;

    public TcpHeartBeatHandler(IDeviceService deviceService){
        this.deviceService = deviceService;
    }

    /**
     * 用户事件触发的处理器
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("******userEventTriggered***start:{}", DateUtils.getTime());
        String channelId = ctx.channel().id().asShortText();
        log.info("***userEventTriggered***channelId：{}", channelId);
        //判断evt是否属于IdleStateEvent，用于触发用户事件，包含读空闲，写空闲，读写空闲
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                //读空闲
                log.info("***userEventTriggered***进入读空闲，本实例当前连接数：{}", ChannelTcpMap.channelTcpNum);
                //删除和关闭通道
                deviceService.removeChannel(ctx);
            } else if (event.state() == IdleState.WRITER_IDLE) {
                //写空闲，不做处理
                log.info("***userEventTriggered***进入写空闲，本实例当前连接数：{}", ChannelTcpMap.channelTcpNum);
            } else if (event.state() == IdleState.ALL_IDLE) {
                log.info("***userEventTriggered***进入读写都空闲，本实例当前连接数：{}：" + ChannelTcpMap.channelTcpNum);
                //先不做处理，在读空闲处理
                //deviceService.removeChannel(ctx);
            }
            log.info("******userEventTriggered***end:{}", DateUtils.getTime());
        }
    }
}
